package dryven.persistence;

import javax.persistence.EntityManager;

import dryven.config.DatabaseConfiguration;
import dryven.persistence.provider.PersistenceProvider;

/**
 * does lazy loading for an EntityManager of a
 * specified DatabaseConfiguration. Also performs cleanup
 * @author bwindels
 *
 */
public class PersistenceConnection {
	private EntityManager _entityManager;
	private PersistenceProvider _provider;
	private DatabaseConfiguration _config;
	
	public PersistenceConnection(PersistenceProvider provider,
			DatabaseConfiguration config) {
		super();
		_provider = provider;
		_config = config;
	}

	public EntityManager getEntityManager() {
		if(_entityManager==null || !_entityManager.isOpen()) {
			_entityManager = _provider.createEntityManager(_config);
		}
		return _entityManager;
	}
	
	public void cleanup() {
		if(_entityManager!=null && _entityManager.isOpen()) {
			_entityManager.close();
		}
	}
}
